package com.dbapp.garden.controller.contract;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import com.dbapp.garden.config.security.PermissionUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.dbapp.garden.common.RenderJSON;
import com.dbapp.garden.entity.GardenSmallTicketInfo;
import com.dbapp.garden.service.IGardenSmallTicketInfoService;

@Controller
public class SmallTicketController extends BaseContractController {

    @Autowired
    IGardenSmallTicketInfoService ticketService;

    @GetMapping("/smallticketinfo")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_SMALL_TICKET') or hasAuthority('PERMISSION_SMALL_TICKET_VIEW')")
    public Map<String, ?> editSmallTicketInfo(@SessionAttribute("user") PermissionUser user) {

        GardenSmallTicketInfo ticketInfo = ticketService.findByGardenId(user.getGardenId());
        return RenderJSON.makeStandMap(1, "获取成功！", ticketInfo);
    }

    @PostMapping("/smallticketedit")
    @ResponseBody
    @PreAuthorize("hasAuthority('PERMISSION_SMALL_TICKET_EDIT')")
    public Map<String, ?> editSmallTicket(@SessionAttribute("user") PermissionUser user,
                                          @RequestBody @Valid GardenSmallTicketInfo ticketInfo) {
        if (ticketInfo == null) {
            return RenderJSON.makeStandMap(1, "对不起，编辑失败！", "error");
        }

        if (StringUtils.isBlank(ticketInfo.getSmallticket())) {
            return RenderJSON.makeStandMap(1, "对不起，编辑失败,小票内容为空！", "error");
        }

        ticketInfo.setUpdateDate(new Date());
        ticketInfo.setGarden_id(user.getGardenId());
        if (ticketInfo.getId() != null) {
            GardenSmallTicketInfo tInfo = ticketService.findById(ticketInfo.getId());
            if (tInfo == null) {
                return RenderJSON.makeStandMap(1, "对不起，编辑失败！", "error");
            }

            if (!tInfo.getGarden_id().equals(user.getGardenId())) {
                return RenderJSON.makeStandMap(1, "对不起，您没有权限！", "error");
            }
        }
        ticketInfo = ticketService.saveSmallTicket(ticketInfo);
        if (ticketInfo != null) {
            return RenderJSON.makeStandMap(1, "恭喜您，编辑成功！", "ok");
        } else {
            return RenderJSON.makeStandMap(1, "对不起，编辑失败！", "error");
        }

    }
}
